#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int longestValidParentheses(string s) {
        int len = s.length();
        int maxLen = 0;
        stack<int> stk;
        int start = -1;
        for(int i = 0; i < len; i++) {
            if(s[i] == '(') {
                stk.push(i);
            } else {
                if(stk.empty()) {
                    start = i;
                } else {
                    stk.pop();
                    if(stk.empty()) {
                        maxLen = max(maxLen, i - start);
                    } else {
                        maxLen = max(maxLen, i - stk.top());
                    }
                }
            }
        }
        return maxLen;
    }
};

int main() {
    Solution s;
    string str = ")()())";
    cout<<s.longestValidParentheses(str)<<endl;
    return 0;
}